
#include "NetworkManager.h"

#include "PacketObjectDestroy.h"
#include "PacketObjectMove.h"
#include "PacketObjectSpawn.h"
#include <assert.h>
#include <iostream>
NetworkManager::NetworkManager(void)
	:
	m_isRunning(false),
	m_wsaData(),
	m_socket(INVALID_SOCKET)
{
	Init();
}
NetworkManager::~NetworkManager(void)
{
	Shutdown();
}
void NetworkManager::Init(void)
{
	WSAStartup(MAKEWORD(2, 2), &m_wsaData);
	
	m_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
}
void NetworkManager::Shutdown(void)
{
	if (m_socket != INVALID_SOCKET)
		closesocket(m_socket);

	WSACleanup();

	m_isRunning = false;
}
Packet* NetworkManager::ReadPacket(void)
{
	if (!m_packetBuffer.GetSize())
		return 0;

	PACKET_TYPE type = static_cast<PACKET_TYPE>(static_cast<int>(m_packetBuffer));

	Packet* packet = 0;
	if (type == PACKET_TYPE::OBJECT_SPAWN)
		packet = new PacketObjectSpawn(m_packetBuffer);

	else if (type == PACKET_TYPE::OBJECT_MOVE)
		packet = new PacketObjectMove(m_packetBuffer);

	else if (type == PACKET_TYPE::OBJECT_DESTROY)
		packet = new PacketObjectDestroy(m_packetBuffer);

	return packet;
}
void NetworkManager::SendPacket(Packet* packet, SOCKET socket)
{
	char buff[1024];
	int len = packet->Write(buff);
	int ret = send(socket, buff, len, 0);

	//assert(ret != SOCKET_ERROR);
	if (ret == SOCKET_ERROR)
	{
		printf("Last Error:%i \n", WSAGetLastError());
	}

}
void NetworkManager::CopyToBuffer(char* data, int len)
{
	m_packetBuffer.Append(data, len);
}

/*NetworkManager** NetworkManager::GetInstance(void)
{
	static NetworkManager** mgr = new NetworkManager*;
	return mgr;
	return 0;
}*/
bool NetworkManager::IsRunning(void) const
{
	return m_isRunning;
}
SOCKET NetworkManager::GetSocket(void) const
{
	return m_socket;
}
size_t NetworkManager::GetBufferSize(void) const
{
	return m_packetBuffer.GetSize();
}
void NetworkManager::SocketRecvThread(RecvThreadArgs* args)
{
	bool connected = true;
	char buffer[1024];

	while (connected)
	{
		int len = recv(args->socket, buffer, 1024, 0);
		if (len > 0)
			args->mgr->CopyToBuffer(buffer, len);

		else if (len == 0)
			connected = false;

		else
			printf("SOCKET_ERROR=%i\n", WSAGetLastError());
	}
	delete args;
}